<template>
  <el-form :rules="rules" ref="ruleFormRef" :model="ruleForm" label-width="130px" class="demo-ruleForm" status-icon>
    <el-tabs v-model="data.activeName" class="demo-tabs">
      <el-tab-pane label="推荐人选" name="first">
        <el-row :gutter="15">
          <el-col :span="8">
            <el-form-item label="选择用户">
              <!-- <SelectOption :selectValue="ruleForm.cname" :options="options.userAllList" @change-value="changeValue0"></SelectOption> -->
              <user-list-modal
                v-model="ruleForm.cname"
                @update:modelValue="changeValue0"
                :default-users="[]"
                :multiple="false"
                :devType="'platform'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="姓名">
              <el-input placeholder="选择用户自动带出不可编辑" v-model="ruleForm.username" style="width: 100%" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别">
              <SelectOption :selectValue="ruleForm.sexName" :options="options.sexList" @change-value="changeValue1" :disabled="1">
              </SelectOption>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="民族">
              <SelectOption :selectValue="ruleForm.mingzuName" :options="options.minzuList" @change-value="changeValue2">
              </SelectOption>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出生年月">
              <!-- <el-input placeholder="选择用户自动带出不可编辑" v-model="ruleForm.birth" style="width: 100%"  /> -->
              <el-date-picker v-model="ruleForm.birth" format="YYYY-MM-DD" type="date" placeholder="选择日期" clearable
              @change="handleChangeDate" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="政治面貌">
              <SelectOption :selectValue="ruleForm.politicalName" :options="options.politicsList"
                @change-value="changeValue3"> </SelectOption>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="8">
            <el-form-item label="职称">
              <el-input placeholder="选择用户自动带出不可编辑" v-model="ruleForm.professional" style="width: 100%"  disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="行政职务">
              <el-input placeholder="选择用户自动带出不可编辑" v-model="ruleForm.administrative" style="width: 100%"  disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最高学历">
              <el-input placeholder="选择用户自动带出不可编辑" v-model="ruleForm.highesteducation" style="width: 100%"  disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最高学位">
              <el-input placeholder="选择用户自动带出不可编辑" v-model="ruleForm.highestdegree" style="width: 100%"  disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="所从事专业或方向">
              <el-input placeholder="选择用户自动带出不可编辑" v-model="ruleForm.speciality" style="width:100%" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="技术领域">
              <el-input placeholder="选择用户自动带出不可编辑" v-model="ruleForm.technical" style="width: 100%"  disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="从事科研年限">
              <el-input placeholder="选择用户自动带出不可编辑" v-model="ruleForm.research" style="width: 100%" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>

    <el-tabs v-model="data.activeName" class="demo-tabs">
      <el-tab-pane label="推荐单位及意见" name="first">
        <el-row>
          <el-col :span="8">
            <el-form-item label="推荐单位" prop="recommendUnit">

              <popup-tree-input :data="orgAllList" :props="deptForm.popupTreeProps" :prop="deptForm.parentName == null
                          ? $t('message.org.top_menu')
                          : ruleForm.recommendUnit
                        " :node-key="'' + deptForm.parentId" :current-change-handle="changeValue5" />
             
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位联系人" prop="unitContact">
              <user-list-modal
                v-model="ruleForm.unitContact"
                @update:modelValue="changeValue6"
                :default-users="[]"
                :multiple="false"
                :devType="'platform'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="unitContactRel">
              <el-input placeholder="请输入" v-model="ruleForm.unitContactRel" style="width: 100%"  />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="电子邮箱" prop="unitContactEmail">
              <el-input placeholder="请输入" v-model="ruleForm.unitContactEmail" style="width: 100%"  />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="负责人" prop="chargeName">
              <!-- <SelectOption :selectValue="ruleForm.chargeName" :options="options.userAllList"
                @change-value="changeValue4">
              </SelectOption> -->
              <user-list-modal
                v-model="ruleForm.chargeName"
                @update:modelValue="changeValue4"
                :default-users="[]"
                :multiple="false"
                :devType="'platform'"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>

    <el-tabs v-model="data.activeName" class="demo-tabs">
      <el-tab-pane label="推优秀科技人才主要工程科技业绩与科技创新成果(限 2000 字以内)" name="first">
        <el-input v-model="ruleForm.mainKpsResult" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"
          placeholder="请输入" />
      </el-tab-pane>
    </el-tabs>

  </el-form>
</template>

<script lang="ts">
import * as proxy from "@/constants/proxy";
import request from "@/utils/request";
import UserListModal from '@/views/project/components/UserListModal/index.vue';
import PopupTreeInput from '@/views/science/components/PopupTreeInput/index.vue';
import SelectOption from '@/views/science/components/selectOption/index.vue';
import Table from '@/views/science/components/table/table.vue';
import { computed, reactive, ref, watch } from 'vue';
import { useStore } from 'vuex';

export default {
  components: {
    SelectOption,
    Table,
    UserListModal,
    PopupTreeInput
  },
  props:{
    orgAllList: {
      type: Array,
      required: true,
    },
  },
  setup(props, { emit }) {

    const deptForm = {
      parentId: 0,
      parentName: '',
      popupTreeProps: {
        label: 'name',
        children: 'children',
        value: 'id',
        checkStrictly: true,
      },
    }

    const store = useStore() // 获取vuex的数据
    const labelPosition = ref('right')  // 表单label位置
    const data = reactive({
      activeName: ref('first'),  // 弹窗中的tab切换
      dialogVisible: false,

      page: { page: 1, limit: 10, total: 0 },
      ids: [],
      allTableData: [],
      columns: [
        {
          key: 'name',
          width: 140,
          label: '合同名称',
        },
        {
          key: 'changeTime',
          width: 140,
          label: '合同编号',
        },
        {
          key: 'changeNode',
          width: 140,
          label: '项目名称',
        },
        {
          key: 'changeBefore',
          width: 140,
          label: '起止时间',
        },
        {
          key: 'changeAfter',
          width: 140,
          label: '项目负责人',
        },
      ],
    })

    // 弹窗中下拉选择
    let options = reactive({
      userAllList: computed(() => store.state.technologyStrength.userAllList),
      sexList: computed(() => store.state.technologyStrength.sexList),
      minzuList: computed(() => store.state.technologyStrength.minzuList),
      politicsList: computed(() => store.state.technologyStrength.politicsList),
      unitList: computed(() => store.state.technologyStrength.orgAllList),

      unitnameList: [],
      budgetYearlist: [],
      projectnameList: [],
    })

    const ruleForm = reactive(store.state.technologyStrength.award_talentINFO)
    watch(ruleForm, (newValue, oldValue) => {
      // console.log("form值改变22222222了", ruleForm)
      store.commit('technologyStrength/getaward_talentINFO', { ...ruleForm })
    });

    const changeValue0 = (item) => {
      console.log('changeValue0',item);
      ruleForm.cname = item.cname
      ruleForm.username = item.cname
      ruleForm.userId = item.userId
      ruleForm.sex = item.gender
      ruleForm.sexName = item.gendertext
      // ruleForm.mingzu = item.nation
      // ruleForm.birth = item.birth
      // ruleForm.professional = item.technicalTitle
      // ruleForm.administrative = item.selectOrgs
      // ruleForm.highesteducation = item.educationBackground
      getPeople(item.userCode)
    }
    const getPeople = (id) =>{
            return request({
                url: proxy.CHECC_API_CMS + "/user/getList",
                method: "post",
                data:{empcode:id},
            }).then(res =>{
                console.log('res',res.data.data.records[0]);
                let resdata = res.data.data.records[0]
                // data.diaForm.genderId = resdata.gender
                // data.diaForm.gender = resdata.gendertext
                ruleForm.birth = resdata.birth.substring(0,10)
                //     //根据出生日期算年龄
                //     if(data.diaForm.birthdate){
                //         let birthDayTime = new Date(data.diaForm.birthdate).getTime();
                //         let nowTime = new Date().getTime();
                //         data.diaForm.age = Math.ceil((nowTime - birthDayTime) / 31536000000) 
                //     }
                ruleForm.mingzu = resdata.nationDict 
                ruleForm.mingzuName = resdata.nation
                // ruleForm.phone = resdata.phone
                // data.diaForm.highestDegreeId = resdata.educationDict
                ruleForm.highesteducation = resdata.educationBackground
                ruleForm.speciality = resdata.typeOfWork 
                // data.diaForm.workStartDate = resdata.hiredate.substring(0,10) 
                //     //参加工作时间
                //     if(data.diaForm.workStartDate){
                //         let DayTime = new Date(data.diaForm.workStartDate).getTime();
                //         let nowTime = new Date().getTime();
                //         data.diaForm.workExperience = Math.ceil((nowTime - DayTime) / 31536000000)
                //     }
                // data.diaForm.workUnitName = resdata.orgname 
                // data.diaForm.workUnitId = resdata.orgid 
                // data.diaForm.deptName = resdata.deptName  
                // data.diaForm.deptId = resdata.deptId 
                ruleForm.administrative = resdata.selectOrgs 
                // ruleForm.positionId = resdata.technicalDict 
                ruleForm.professional = resdata.technicalTitle   
                // data.diaForm.email = resdata.email  
                ruleForm.political = resdata.politicalDict
                ruleForm.highestdegree = resdata.typeOfWork
                ruleForm.technical = resdata.educationBackground
                 //参加工作时间
                 if(resdata.hiredate){
                        let DayTime = new Date(resdata.hiredate).getTime();
                        let nowTime = new Date().getTime();
                        ruleForm.research = Math.ceil((nowTime - DayTime) / 31536000000)
                    }
                ruleForm.politicalName = resdata.remark
            })
        }

    const changeValue1 = (item) => {
      ruleForm.sex = item.itemValue
      ruleForm.sexName = item.itemText
    }
    const changeValue2 = (item) => {
      ruleForm.mingzu = item.itemValue
      ruleForm.mingzuName = item.itemText
    }
    const changeValue3 = (item) => {
      ruleForm.political = item.itemValue
      ruleForm.politicalName = item.itemText
    }

    const changeValue4 = (item) => {
      ruleForm.chargeId = item.userId
      ruleForm.chargeName = item.cname
    }

    const changeValue5 = (item) => {
      ruleForm.recommendUnit = item.name
      ruleForm.recommendUnitId = item.id
    }

    const changeValue6 = (item) => {
      console.log('item,',item);
      ruleForm.unitContactId = item.userId
      ruleForm.unitContact = item.cname
      ruleForm.unitContactRel = item.phone 
      ruleForm.unitContactEmail = item.email
    }



    let save = () => {
      console.log(1)
    }

    let open = () => {
      console.log(11111)
      data.dialogVisible = true
    }

    //手机号码校验
    var checkPhone = (rule, value, callback) => {
        if (!value) {
                return callback(new Error("手机号不能为空"));
        } else {
            const reg = /^1[3-9][0-9]\d{8}$/;
            // 这里定义的reg变量没有加引号，所以是一种特殊的数据类型，即正则，可以直接用test()方法
            if (reg.test(value)) {
                    callback();
            } else {
                    // 具体错误信息没有提示
                    return callback(new Error("请输入正确的手机号"));
            }
        }
    };
    //邮箱校验
    var checkEmail = (rule, value, callback) => {
        if (!value) {
                return callback(new Error("请输入电子邮箱"));
        } else {
            const reg = /^([a-zA-Z]|[0-9])(\w|\-|\.)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
            // 这里定义的reg变量没有加引号，所以是一种特殊的数据类型，即正则，可以直接用test()方法
            if (reg.test(value)) {
                    callback();
            } else {
                    // 具体错误信息没有提示
                    return callback(new Error("请输入正确的电子邮箱"));
            }
        }
    };
    // 新增
    const rules = reactive({
      recommendUnit: [
        { required: true, message: '请输入单位名称', trigger: ['blur','change'], },
      ],
      unitContact: [
        { required: true, message: '输入单位联系人', trigger: 'blur', },
      ],
      unitContactRel: [
        { validator: checkPhone, trigger: "blur" },
        { required: true,  trigger: 'blur' },
        { min: 11, message: "手机号不足11位", trigger: "blur" },
      ],
      unitContactEmail: [
        { validator: checkEmail, trigger: "blur" },
        { required: true,  trigger: 'blur' },
      ],
      chargeName: [
        { required: true, message: '负责人', trigger: 'change', },
      ],
      mainKpsResult: [
        { required: true, message: '请输入成果', trigger: 'blur', },
      ],

    })

    const ruleFormRef = ref()
    const submitForm = async () => {
      await ruleFormRef.value.validate((valid, fields) => {
        if (valid) {
          emit('valueFlag', true)
          console.log('submit!')
        } else {
          emit('valueFlag', false)
        }
      })
    }

    const handleChangeDate = (val) => {
      const year = val.getFullYear(); // 获取年份
      const month = (val.getMonth() + 1) < 10 ? '0' + (val.getMonth() + 1) : (val.getMonth() + 1); // 获取月份，需要加1
      const day = val.getDate() < 10 ? '0' + val.getDate() : val.getDate(); // 获取日期
      const formattedDate = `${year}-${month}-${day}`;
      ruleForm.birth = formattedDate
      store.commit('technologyStrength/getForm', { ...ruleForm })
    }

    return {
      submitForm,
      open,
      ruleForm,
      rules,
      ruleFormRef,
      labelPosition,
      data,
      options,
      save,
      handleChangeDate,
      deptForm,

      changeValue0,
      changeValue1,
      changeValue2,
      changeValue3,
      changeValue4,
      changeValue5,
      changeValue6
    }
  },
}
</script>
<style lang="scss" scoped>
.demo-form-inline .el-form-item {
  width: 48%;
}

:deep(.labelHeight .el-form-item__label) {
  line-height: 20px;
}

:deep(.el-date-editor.el-input) {
  width: 100%;
}

:deep(.el-date-editor.el-input__inner) {
  width: 100%;
}

:deep(.demo-form-inline .el-select) {
  width: 100%;
  margin: 0;
}

.el-select {
  width: 100%;
  margin: 0;
}

.selectLabel {
  width: 70%;
  min-height: 40px;
  line-height: 40px;
  padding: 0 18px;
  border: 1px solid #ccc;
  border-radius: 6px;
  display: inline-block;
}

.addLabel {
  display: inline-block;
  width: 120px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  background-color: #169bd5;
  border-radius: 6px;
  color: #fff;
  margin-left: 15px;
}

.unitBox {
  width: 100%;
  margin: 30px 0;

  .title {
    padding: 15px 0;
    border-bottom: 1px solid #ccc;
  }

  .tagBox {
    line-height: 40px;
    margin-top: 15px;
    border: 1px solid #ccc;
    border-radius: 8px;
    padding: 10px 15px;
  }
}

.el-tag {
  margin-right: 10px;
}

.selectLabel {
  width: 70%;
  min-height: 40px;
  line-height: 40px;
  padding: 0 15px;
  border: 1px solid #ccc;
  border-radius: 6px;
  display: inline-block;
}

.content-box {
  width: 200px;
  height: 33px;
  padding: 5px;
  box-sizing: border-box;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.select {
  color: #eee;
}

.align-center {
  align-items: center;
}

.space-between {
  justify-content: space-between;
}

.mt20 {
  margin-top: 20px;
}

.flex {
  display: flex;
}

.handle {
  position: absolute;
  top: 17px;
  right: 20px;
  display: flex;
  align-items: center;
}

.search-box {
  display: flex;
  justify-content: end;
  align-items: center;
  margin-bottom: 10px;
}
</style>
